//
//  BookCityViewController.m
//  FunRead
//
//  Created by  King on 15/5/22.
//  Copyright (c) 2015年 华东伟. All rights reserved.
//

#import "BookCityViewController.h"
#import "BookCityCell.h"
#import <AFNetworking/AFNetworking.h>
#import "MaleAndFemaleViewController.h"
#import "SANetWorkingTask.h"
#import <UIImageView+AFNetworking.h>
#import "BookDetailController.h"
#import "BookListViewController.h"
#import "CategoryDetailViewController.h"
#import "AudioBookViewController.h"
#import "SearchByChooseViewController.h"
// 遵循自定义协议
@interface BookCityViewController ()<UITableViewDataSource, UITableViewDelegate, MyBookCityViewDelegate, UISearchBarDelegate>

// 定义table
@property(nonatomic, retain)UITableView *table;

@end

@implementation BookCityViewController
- (void)dealloc
{
    [_table release];
    [_mySearch release];
    [_tableArray release];
    [super dealloc];
}

- (void)awakeFromNib
{
    [super awakeFromNib];
    // 初始化tableArray
    self.tableArray = [NSMutableArray array];
    
}

- (void)createSearchBar
{
    self.mySearch = [[UISearchBar alloc]initWithFrame:CGRectMake(0,  0 , [UIScreen mainScreen].bounds.size.width, 30)];
    [self.mySearch setBackgroundColor:[UIColor grayColor]];
    [self.mySearch setPlaceholder:@"输入小说名或者作者"];
    self.mySearch.delegate = self;
    self.mySearch.autocapitalizationType = UITextAutocorrectionTypeYes;
    self.mySearch.keyboardType = UIKeyboardTypeTwitter;
    self.mySearch.showsCancelButton = NO;
    [self.view addSubview:self.mySearch];
    [self.mySearch release];
    
}

#pragma mark - Search的协议
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    [self.mySearch resignFirstResponder];
    SearchByChooseViewController *sea
    = [[SearchByChooseViewController alloc]init];
    sea.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:sea animated:YES];
     [sea release];

}

- (void)viewWillAppear:(BOOL)animated
{
    [self createSearchBar];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // 设置导航栏为不透明
    [self.navigationController.navigationBar setTranslucent:NO];
    // 改变默认显示item
    
    self.view.frame = CGRectMake(5, 0, [UIScreen mainScreen].bounds.size.width - 10, [UIScreen mainScreen].bounds.size.height );
    // 设置tabbar为不透明
    [self.navigationController.tabBarController.tabBar setTranslucent:NO];
    
    
    //设置导航栏上的标题
    self.navigationItem.title = @"悦读书城";
    // 判断有误网络
    //    Reachability *re =
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self dataRequest];
    [self createTable];
    [self createSearchBar];
    
}

#pragma mark -请求数据
- (void)dataRequest
{
    
    [SANetWorkingTask request:@"http://vip.hentr.com/zhuibook/api/zhuibook/GetBookStore.do" parmaters:@"version=1.3" block:^(NSDictionary *result) {
        self.tableArray = [[result objectForKey:@"response"] objectForKey:@"ReturnData"];
        
        
        [self.table reloadData];
    }];
    
}
#pragma mark -
#pragma mark - 创建table
- (void)createTable
{
    self.table = [[UITableView alloc]initWithFrame:CGRectMake(5, 30, self.view.frame.size.width, self.view.frame.size.height - 49 - 64 - 30 ) style:UITableViewStylePlain];
    self.table.delegate = self;
    self.table.dataSource = self;
    self.table.separatorStyle = UITableViewCellSeparatorStyleNone;
//    [self.table setBackgroundColor:[UIColor colorWithRed:0.9 green:0.1 blue:0.3 alpha:1]];
    UIColor *color = [UIColor colorWithPatternImage:[UIImage imageNamed:@"70.jpg"]];
    self.table.backgroundColor = color;
    [self.view addSubview:self.table];
    
    // 隐藏滑动条
    self.table.showsVerticalScrollIndicator = NO;
    // 开始设置headertable
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 100)];
    // 导航栏label
    NSArray *array = @[@"悦排行", @"悦男生", @"悦女生", @"悦有声"];
    for (int i = 0; i < 4; i++) {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 50) / 4 * i  + (14 * i + 1), 80, (self.view.frame.size.width - 50) / 4, 20)];
        label.text = array[i];
        label.textColor = [UIColor lightGrayColor];
        label.textAlignment = 1;
        [view addSubview:label];
        [label release];
    }
    
//    UIColor *color = [UIColor colorWithPatternImage:[UIImage imageNamed:@"16.png"]];
//    view.backgroundColor = [UIColor whiteColor];
    // 设置背景色
//        view.alpha = 0.5;
    // 定义显示title的label
    
    // 创建分段对象
    UISegmentedControl *segmentedControl = [[UISegmentedControl alloc]initWithFrame:CGRectMake(5, 10, [UIScreen mainScreen].bounds.size.width - 20, 60)];
    segmentedControl.layer.cornerRadius = 7;
    segmentedControl.tintColor = [UIColor clearColor];
    [segmentedControl insertSegmentWithImage:[[UIImage imageNamed:@"排行榜.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] atIndex:0 animated:YES];
    [segmentedControl insertSegmentWithImage:[[UIImage imageNamed:@"男生.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]  atIndex:1 animated:YES];
    [segmentedControl insertSegmentWithImage:[[UIImage imageNamed:@"女生.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] atIndex:2 animated:YES];
    [segmentedControl insertSegmentWithImage:[[UIImage imageNamed:@"有声.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] atIndex:3 animated:YES];
//    UIColor *color = [UIColor colorWithPatternImage:[UIImage imageNamed:@"16.png"]];
//    segmentedControl.backgroundColor = color ;
    
    // 设置title颜色
//    segmentedControl.tintColor = [UIColor whiteColor];
    segmentedControl.alpha = 1;
    // 粘贴来的改变标题的字体
    NSDictionary *textDic = [NSDictionary dictionaryWithObjectsAndKeys:
                             [[UIColor blackColor]       colorWithAlphaComponent:0.6f],UITextAttributeTextColor,
                             [UIColor blackColor],UITextAttributeTextShadowColor,
                             [NSValue valueWithUIOffset:UIOffsetMake(1, 0)],UITextAttributeTextShadowOffset,
                             [UIFont systemFontOfSize:20],UITextAttributeFont,nil];
    
    [segmentedControl setTitleTextAttributes:textDic forState:UIControlStateNormal];
    //设置样式
    segmentedControl.segmentedControlStyle = UISegmentedControlStyleBezeled;//?????????
    // 设置在点击后是否恢复原样
    segmentedControl.momentary = YES;
    
    // 可触摸
    segmentedControl.multipleTouchEnabled = NO;
    
    [segmentedControl addTarget:self action:@selector(SelectButton:) forControlEvents:UIControlEventValueChanged];
    
    [view addSubview:segmentedControl];
    [segmentedControl release];
    [self.table setTableHeaderView:view];
    //    [self.table setHidden:YES];
    
        //    self.table.bounces = NO;
    [self.table release];
}
#pragma mark - 点击table头跳转事件实现
- (void)SelectButton:(UISegmentedControl *)sender
{
    NSInteger index = sender.selectedSegmentIndex;
    //    NSLog(@"%ld, %@", (long)index, [sender titleForSegmentAtIndex:index]);
    
    if (index == 0) {
        // 跳到排行榜页面
        // 不需要传值, 直接跳
        BookListViewController *bookList = [[BookListViewController alloc] init];
        bookList.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:bookList animated:YES];
        
    } else if (index == 1 || index == 2)
    {
        // 跳到男生页面或者女生页面
        MaleAndFemaleViewController *controll = [[MaleAndFemaleViewController alloc] init];
        controll.hidesBottomBarWhenPushed = YES;
        controll.cid = [NSString stringWithFormat:@"%ld", index];
        [self.navigationController pushViewController:controll animated:YES];
        [controll release];
    } else if (index == 3)
    {
        // 跳转到有声小说页面
        AudioBookViewController *audioBook = [[AudioBookViewController alloc] init];
        [self.navigationController pushViewController:audioBook animated:YES];
        [audioBook release];
    }
    
}

#pragma mark - 实现协议点击图片跳转到书籍详情
- (void)pushBookDetailView:(NSString *)bookId
{
    // 跳转书籍详情页面, 给书籍详情页面传递bookId过去
    BookDetailController *detail = [[BookDetailController alloc]init];
    detail.str = bookId;
    detail.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detail animated:YES];
    [detail release];
    
}

#pragma mark - 点击行跳转界面:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    // 点击某行跳到相对应的section所在的视图
    // 需要传值:storyType对应的value传给下一个页面的pxId
   NSMutableDictionary *dic =  [self.tableArray objectAtIndex:indexPath.section];
    
    NSString *title = [dic objectForKey:@"storeTitle"];
    NSString *type = [NSString stringWithFormat:@"%@", [dic objectForKey:@"storeType"]];
    
    CategoryDetailViewController *detail = [[CategoryDetailViewController alloc]init];
    // 传值
    detail.pxId = type;
    detail.choice = 2;
    
    detail.categoryName = title;
    
    // 影藏tabbar, 回来时就又有了
    detail.hidesBottomBarWhenPushed =YES;
    // 跳转页面
    [self.navigationController pushViewController:detail animated:YES];
    [detail release];

    
    }
#pragma mark - talbeview的协议
#pragma mark - section数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.tableArray.count == 0) {
        return 0;
    }
   
    return self.tableArray.count;
    
}

#pragma mark- 每个分区的颜色
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(5, 0, self.view.frame.size.width - 10, 25)];
    //设置cell颜色
//    view.backgroundColor = [UIColor cyanColor];
    // 设置背景色
    view.alpha = 0.5;
    // 定义显示title的label
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 5, 100, 20)];
//    label.backgroundColor = [UIColor cyanColor];
    label.layer.cornerRadius = 5;
    [view addSubview:label];
    NSMutableDictionary *dic = [self.tableArray objectAtIndex:section];
    NSString *title = [dic objectForKey:@"storeTitle"];
    label.text = title;
    label.font = [UIFont systemFontOfSize:20];
    return view;
    
}

#pragma mark- 每个分区的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.tableArray.count == 0) {
        return 30;
    }
    return 1;
}

#pragma mark - 给cell赋值
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIndentity = @"cell";
    BookCityCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentity];
    if (!cell) {
        cell = [[BookCityCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIndentity];
        //设置cell颜色
        cell.contentView.frame = CGRectMake(5, 0, [UIScreen mainScreen].bounds.size.width - 10, 120);
        cell.layer.cornerRadius = 7;
//        cell.contentView.backgroundColor = [UIColor whiteColor];
        // 设置背景色
//        cell.contentView.alpha = 0.5;
        //        cell.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 130);
    }
    
    //将cell设置成点击时不变色
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (self.tableArray.count > 0) {
        
        // 取出该行第一个view数据对应的字典
        NSMutableDictionary *dic = [[[self.tableArray objectAtIndex:indexPath.section] objectForKey:@"storeList"] objectAtIndex:indexPath.row] ;
        //    NSLog(@"%@", dic);
        
        // 给view赋值
        [cell.leftView.image setImageWithURL:[NSURL URLWithString:[dic objectForKey:@"imageUrl"]] placeholderImage:[UIImage imageNamed:@"loading.gif"]];
        cell.leftView.nameLabel.text = [dic objectForKey:@"bookName"];
        cell.leftView.authorLabel.text = [dic objectForKey:@"author"];
        
        // 给cell上的自定义视图bookId属性赋值, 便于跳页面时传值
        cell.leftView.bookId = [NSString stringWithFormat:@"%@",[dic objectForKey:@"bookid"]];
        // 协议设置代理人
        cell.leftView.delegate = self;
        cell.leftView.image.layer.cornerRadius = 10;
        cell.leftView.image.layer.masksToBounds = YES;
        // 取出该行第二个view数据对应的字典
        NSMutableDictionary *midDic = [[[self.tableArray objectAtIndex:indexPath.section] objectForKey:@"storeList"] objectAtIndex:indexPath.row + 1] ;
        
        // 给第二个view赋值
        [cell.midView.image setImageWithURL:[NSURL URLWithString:[midDic objectForKey:@"imageUrl"]] placeholderImage:[UIImage imageNamed:@"loading.gif"]];
        cell.midView.nameLabel.text = [midDic objectForKey:@"bookName"];
        cell.midView.authorLabel.text = [midDic objectForKey:@"author"];
        
        // 给cell上的自定义视图bookId属性赋值, 便于跳页面时传值
        cell.midView.bookId = [NSString stringWithFormat:@"%@",[midDic objectForKey:@"bookid"]];
        cell.midView.delegate = self;
        cell.midView.image.layer.cornerRadius = 10;
        cell.midView.image.layer.masksToBounds = YES;
        
        // 取出该行第三个view数据对应的字典
        NSMutableDictionary *rightDic = [[[self.tableArray objectAtIndex:indexPath.section] objectForKey:@"storeList"] objectAtIndex:indexPath.row + 2] ;
        //    NSLog(@"%@", rightDic);
        
        [cell.rightView.image setImageWithURL:[NSURL URLWithString:[rightDic objectForKey:@"imageUrl"]] placeholderImage:[UIImage imageNamed:@"loading.gif"]];
        cell.rightView.nameLabel.text = [rightDic objectForKey:@"bookName"];
        cell.rightView.authorLabel.text = [rightDic objectForKey:@"author"];
        
        //给cell上的自定义视图bookId属性赋值, 便于跳页面时传值
        cell.rightView.bookId = [NSString stringWithFormat:@"%@", [rightDic objectForKey:@"bookid"]];
        cell.rightView.delegate = self;
        cell.rightView.image.layer.cornerRadius = 10;
        cell.rightView.image.layer.masksToBounds = YES;
        
    }
    return cell;
}


#pragma mark - 定义每g个分区的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

#pragma mark - 定义每行的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 160;
}

@end
